package x7.heatctrl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Manages the Loging to the db.
 * If the db is available it will use the db connection, 
 * if not it will save the statement either in RAM or Disk and write it later.
 * 
 * @author Anwender
 *
 */
public class DBFile {

	/** singleton instance */
	public static DBFile INSTANCE = new DBFile();
	
	// file to hold statements on disk
	private File file = new File(".dblog");
	
	// List to hold statements in memory
	private List<String> log = new LinkedList<String>();

	/**
	 * adds a statement to be executed in the db
	 * @param sql
	 */
	public synchronized void add(String sql) {
		
		// do we have a db-url?
		if (System.getProperty("db.heat.url")==null) {
			System.out.println(sql);
			return;
		}
		// ram or disk?
		boolean useRam = System.getProperty("writeDbLogInRam", "true").startsWith("t");
		DB db = DB.getDb("heat");
		try {
			if (useRam) {
				for (String cmd:log) db.executeUpdate(cmd);
				log.clear();
			}
			else if (file.exists()) {
				BufferedReader in = null;
				try {
					in = new BufferedReader(new FileReader(file));
					String line=null;
					while ((line=in.readLine())!=null) {
						if (line.length()>0)
						  db.executeUpdate(line.trim());
					}
					in.close();
					file.delete();
				} finally { if (in!=null) in.close();}
			}
			db.executeUpdate(sql);
		}
		catch (Exception ex) {
			if (useRam)
			{
			   if (log.size()>2000) log.remove(0);
			   log.add(sql);
			}
			else {
				FileWriter fw=null;
				try {
					fw = new FileWriter(file, true);
					fw.write(sql+"\n");
					fw.close();
				} catch (IOException e) {
					if (fw!=null) {
						try {
							fw.close();
						} catch (IOException e1) { e1.printStackTrace(); }
					}
				}
			}
		}
	}


}
